package light.head.controller.site;

import java.io.FileOutputStream;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.site.EnergyConservationDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.EnergyConservation;
import light.head.model.FileInfo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
/**
 *	节能减排 
 */
@Controller
@RequestMapping(Url.ENERGYCONSERVATION)
public class EnergyConservationController extends SupporterController{
		private EnergyConservationDAO ecDAO;
		private final static String energyconservation_photo_path = "upload/energyCpnsePhoto/";
		private final static String energyconservation_file_path = "upload/energyCpnseFile/";
		
		@RequestMapping(value = Url.INIT)
		public ModelAndView init(HttpServletRequest request, HttpServletResponse response) throws Exception {
			return new ModelAndView(Url.ENERGYCONSERVATION_INIT);
		}

		@RequestMapping(Url.QUERY)
		public ModelAndView query(HttpServletRequest request, HttpServletResponse response) throws Exception {
			PageBean pb = createPageBean(request);
			Map<String, String> map = createQueryMapByParmName(request, Parm.TITLE, Parm.TIME1, Parm.TIME2,Parm.DELETED);
			if (ecDAO.findByMap(map, pb) == RESULT.SUCCESS){
				request.setAttribute(Parm.PAGE_BEAN, pb);
			}		
			return new ModelAndView(Url.ENERGYCONSERVATION_LIST);
		}
		
		@RequestMapping(Url.EDIT)
		public ModelAndView edit(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
			if (null != code) {
				EnergyConservation ec = ecDAO.get(code);
				request.setAttribute(Parm.ENERGYCONSERVATION, ec);
			}
			return new ModelAndView(Url.ENERGYCONSERVATION_EDIT);
		}
		
		@RequestMapping(value = Url.SAVE)
		public void save(EnergyConservation ec,HttpServletRequest request, HttpServletResponse response) throws Exception {
			RESULT result = RESULT.ERROR;
			if(ec.getCode() != null){
				result=ecDAO.upd(ec);
			}else{
				Date date=new Date();
				ec.setDeleted(false);
				ec.setCt(date);
				ec.setTopTime(date);
				ec.setCu(cu_code(request));
				result=ecDAO.add(ec);
			}
			if(result==RESULT.SUCCESS){
				print(response, Msg.SUCCESS);
			}else{
				print(response, Msg.ERROR);
			}
		}
		
		@RequestMapping(value = Url.DELETE)
		public void delete(Integer code,Byte type,HttpServletRequest request, HttpServletResponse response) throws Exception {
			RESULT result = RESULT.ERROR;
			if(code!=null){
				EnergyConservation ec = ecDAO.get(code);
				ec.setDeleted(true);
				result=ecDAO.upd(ec);
			}
			if(result==RESULT.SUCCESS){
				print(response, Msg.SUCCESS);
			}else{
				print(response, Msg.ERROR);
			}
		}
		//置顶
		@RequestMapping(value = Url.ENERGYCONSERVATIONTOP)
		public void energyconservationTop(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
			RESULT result = RESULT.ERROR;
			if (code != null) {
				EnergyConservation ec = ecDAO.get(code);
				ec.setTopTime(new Date());
				result = ecDAO.upd(ec);
			}
			if (result == RESULT.SUCCESS) {
				print(response, Msg.SUCCESS);
			} else {
				print(response, Msg.ERROR);
			}
		}
		// 单个文件保存
		@Transactional
		@RequestMapping(Url.UPLOAD)
		public void upload(HttpServletRequest request, HttpServletResponse response) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile pohto = multipartRequest.getFile(Parm.UPLOAD);
			String type = request.getParameter(Parm.TYPE);
			String name = pohto.getOriginalFilename();
			if (isNotNull(name)) {
				String ext = name.substring(name.lastIndexOf(Sys.DOT) + 1);
				if (!ext.toUpperCase().equals(Sys.JPG)&& !ext.toUpperCase().equals(Sys.GIF)&& !ext.toUpperCase().equals(Sys.JPEG)
						&& !ext.toUpperCase().equals(Sys.BMP)
						&& !ext.toUpperCase().equals(Sys.PNG)
						&& !ext.toUpperCase().equals(Sys.XLSX)
						&& !ext.toUpperCase().equals(Sys.XLS)
						&& !ext.toUpperCase().equals(Sys.DOCX)
						&& !ext.toUpperCase().equals(Sys.DOC)
						&& !ext.toUpperCase().equals(Sys.PDF)
						&& !ext.toUpperCase().equals(Sys.PPT)
						&& !ext.toUpperCase().equals(Sys.RAR)
						&& !ext.toUpperCase().equals(Sys.ZIP)) {
					print(response, Msg.J_FILE_TYPE_ERROR);
					return;
				}
				name = name.substring(0, name.lastIndexOf(Sys.DOT));

				UUID u = UUID.randomUUID();
				String uuid = u.toString().replace("-", "");
				String path = (type.equals(Sys.FILE) ? energyconservation_file_path : energyconservation_photo_path) + uuid + Sys.DOT + ext;
				String savePath = ConfigParm.getProjectPath() + path;
				FileOutputStream fo;
				int size = 0;
				try {
					fo = new FileOutputStream(savePath);
					size = pohto.getBytes().length;
					fo.write(pohto.getBytes());
					fo.close();
				} catch (Exception e) {
					print(response, Msg.J_ERROR);
					e.printStackTrace();
					throw new RuntimeException();
				}

				FileInfo f = new FileInfo();
				f.setDeleted(false);
				f.setExt(ext);
				f.setName(name);
				f.setUuid(uuid);
				f.setCt(new Date());
				if (type.equals(Sys.FILE)) {
					f.setType(Sys.B_ONE);
					f.setModule(Parm.ENERGYCONSERVATION_FILE);
				} else {
					f.setType(Sys.B_TWO);
					f.setModule(Parm.ENERGYCONSERVATION_PHOTO);
				}
					f.setCu(cu_code(request));
					f.setOc(cu_organCode(request));
					f.setSize(size);
					ecDAO.add(f);

					StringBuffer result = new StringBuffer();
					result.append("<script type=\"text/javascript\">");
					if (isNotNull(path)) {
						result.append("window.parent.CKEDITOR.tools.callFunction("
								+ request.getParameter("CKEditorFuncNum") + ",'" + path
								+ "',''" + ")");
						result.append("</script>");
						result.append(path);
					} else {
						result.append("alert(\"上传失败，文件类型需要jpg、gif或png\")");
						result.append("</script>");
					}
					response.setHeader("Content-Type", "text/html; charset=UTF-8");
					print(response, result.toString());

				} else {
					print(response, Msg.J_ERROR);
				}
		}
		
		@Autowired
		public void setEcDAO(EnergyConservationDAO ecDAO) {
			this.ecDAO = ecDAO;
		}
}
